package com.hetao.jmb2c.interceptors;

import com.hetao.jmb2c.exceptions.BusinessException;
import com.hetao.jmb2c.handlers.BaseContextHandler;
import com.hetao.jmb2c.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    /**
     * JWT工具类，用于解析和验证令牌
     */
    @Resource
    private JwtUtil jwtUtil;

    /**
     * 拦截器前置处理
     * 
     * 处理流程：
     * 1. 从Authorization头获取令牌
     * 2. 检查令牌是否存在
     * 3. 移除Bearer前缀
     * 4. 解析令牌获取用户ID
     * 5. 设置用户ID到线程上下文
     * 
     * @param request HTTP请求
     * @param response HTTP响应
     * @param handler 目标处理器
     * @return 是否继续处理请求
     * @throws Exception 处理异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("uri:{}",request.getRequestURI());
        // 从请求头获取token
        String token = request.getHeader("Authorization");
        log.info("token:{}", token);

        // 检查令牌是否存在
        if(token == null || token.isEmpty()){
            log.info("uri:{}", request.getRequestURI());
            throw new BusinessException("token为空");
        }

        // 解析token，获取用户ID
        token = token.replace("Bearer ", "");
        Claims claims = jwtUtil.parseToken(token);
        Long id = claims.get("id", Long.class);
        log.info("id:{}", id);
        
        // 设置用户ID到线程上下文
        BaseContextHandler.set(id);
        return true;
    }
}
